package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"ota-client/internal/client"
	"ota-client/internal/config"
	"ota-client/internal/logger"
)

var (
	configFile = flag.String("f", "config.yaml", "配置文件路径")
	version    = "1.0.0"
	buildTime  = "unknown"
)

func main() {
	flag.Parse()

	// 显示版本信息
	fmt.Printf("OTA Client v%s (Build: %s)\n", version, buildTime)

	// 加载配置
	cfg, err := config.LoadConfig(*configFile)
	if err != nil {
		log.Fatalf("加载配置文件失败: %v", err)
	}

	// 初始化日志
	logger.Init(cfg.Client.LogLevel)

	// 创建OTA客户端
	otaClient := client.NewOTAClient(cfg)

	// 创建信号通道用于优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// 启动OTA客户端
	log.Printf("启动OTA客户端，设备SN: %s, 产品ID: %s", cfg.Device.SN, cfg.Device.ProductID)
	log.Printf("OTA服务器: %s", cfg.Server.URL)
	log.Printf("检查间隔: %d秒", cfg.Client.CheckInterval)

	// 启动定时检查
	ticker := time.NewTicker(time.Duration(cfg.Client.CheckInterval) * time.Second)
	defer ticker.Stop()

	// 立即执行一次检查
	log.Println("执行初始OTA检查...")
	otaClient.CheckAndUpdate()

	// 主循环
	for {
		select {
		case <-ticker.C:
			log.Println("执行定期OTA检查...")
			otaClient.CheckAndUpdate()
		case <-quit:
			log.Println("接收到退出信号，正在关闭...")
			return
		}
	}
}
